-- lua 模块化扩展
-- Author: Colocasia
-- Date: 2019-07-18
local log = require "log";

local meta = {
    __index = function(t, k)
        if k == "__modules" then return end
		local cmd = k;
        local f;
        for _, module in pairs(t.__modules or {}) do
            if module[cmd] then
                f = module[cmd];
                break;
            end 
        end
        log.notice("[MODULE]execute module %s->%s", type(f), k);
		t[k] = f;
		return f;
	end
};

local function module(root, key)
    local key = key
    assert(type(key) == "string", "invalid arg! mod must be a string path");
    local mod = require(key);
    mod = type(mod.new) == "function" and mod.new() or mod;
    assert(type(mod) == "table", "invalid module");

    if not root.__modules then
        root.__modules = {};
        root.__modules.__root = root.__index;
        setmetatable(root, meta);
    end

    root.__modules[key] = mod;
    assert(nil == mod.__root, "this module have been registered!");
    mod.__root = root;
    mod.root = function (mod)
        return mod.__root;
    end
end

return module;
